import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ProjectShare } from './project-share.entity';
import { Project } from './project.entity';
import { User } from '../user/user.entity';
import { v4 as uuidv4 } from 'uuid';
import * as QRCode from 'qrcode';

@Injectable()
export class ProjectShareService {
  constructor(
    @InjectRepository(ProjectShare)
    private projectShareRepository: Repository<ProjectShare>,
  ) {}

  async createShare(project: Project, sharedBy: User): Promise<ProjectShare> {
    // 检查是否已经存在该用户对该项目的分享
    const existingShare = await this.projectShareRepository.findOne({
      where: {
        project: { id: project.id },
        sharedBy: { id: sharedBy.id },
        isActive: true
      }
    });

    if (existingShare) {
      return existingShare;
    }

    // 生成唯一的分享标识符
    const shareToken = uuidv4();
    
    // 生成二维码链接
    const qrCodeUrl = `${process.env.BASE_URL || 'http://localhost:8080'}/pages/submit.html?share=${shareToken}`;
    
    // 生成二维码数据
    const qrCodeData = await QRCode.toDataURL(qrCodeUrl);

    const projectShare = this.projectShareRepository.create({
      project,
      sharedBy,
      shareToken,
      qrCodeData,
      isActive: true
    });

    return this.projectShareRepository.save(projectShare);
  }

  async findByShareToken(shareToken: string): Promise<ProjectShare | null> {
    return this.projectShareRepository.findOne({
      where: { shareToken, isActive: true },
      relations: ['project', 'sharedBy', 'project.fieldTypes', 'project.formConfig', 'project.formConfig.fieldTypes']
    });
  }

  async findByUser(user: User): Promise<ProjectShare[]> {
    return this.projectShareRepository.find({
      where: { sharedBy: { id: user.id }, isActive: true },
      relations: ['project', 'sharedBy']
    });
  }

  async findByProject(project: Project): Promise<ProjectShare[]> {
    return this.projectShareRepository.find({
      where: { project: { id: project.id }, isActive: true },
      relations: ['project', 'sharedBy']
    });
  }

  async deactivateShare(id: number): Promise<void> {
    await this.projectShareRepository.update(id, { isActive: false });
  }

  async reactivateShare(id: number): Promise<void> {
    await this.projectShareRepository.update(id, { isActive: true });
  }
}